#include "DlgType.h"
#include "PublicData.h"
#include <math.h>
#include <wx/statbox.h>
#include <wx/sizer.h>
#include <wx/stattext.h>
#include <wx/msgdlg.h>
//(*InternalHeaders(DlgType)
#include <wx/intl.h>
#include <wx/string.h>
//*)

//(*IdInit(DlgType)
//*)

const wxString CDlgType::TABLENAME=_T("type");
#define TYPE_MENU _T("菜式类别")
#define TYPE_CASH _T("收支类别")
const wxString WINDOWS_TEXT = _T("类别管理模块");
//控件ID
const long CDlgType::IDC_BTN_ADD_MOD= wxNewId();
const long CDlgType::IDC_BTN_EXIT= wxNewId();
const long CDlgType::IDC_BTN_SEARCH= wxNewId();
const long CDlgType::IDC_BTN_DEL= wxNewId();
const long CDlgType::IDC_COMBO_SEARCH= wxNewId();
const long CDlgType::IDC_COMBO_ID= wxNewId();
const long CDlgType::IDC_EDIT_NAME= wxNewId();
const long CDlgType::IDC_EDIT_SEARCH= wxNewId();
const long CDlgType::IDC_LIST= wxNewId();

BEGIN_EVENT_TABLE(CDlgType,wxDialog)
    //(*EventTable(DlgType)
    //*)
END_EVENT_TABLE()

CDlgType::CDlgType(wxWindow* parent,wxWindowID id)
    :m_addormod_(-1)
{
    //(*Initialize(DlgType)
    Create(parent, id, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER|wxCLOSE_BOX|wxMAXIMIZE_BOX|wxMINIMIZE_BOX, _T("id"));
    //*)
    SetTitle(WINDOWS_TEXT);
    SetWindowStyle(GetWindowStyle()|wxRESIZE_BORDER|wxCLOSE_BOX|wxMAXIMIZE_BOX|wxMINIMIZE_BOX);
    CreateCtrlAndEvent();
    EnableAllCtrl(false);
    InitComboBoxAndListCtrl();
}

CDlgType::~CDlgType()
{
    //(*Destroy(DlgType)
    //*)
}

void CDlgType::CreateCtrlAndEvent()
{
    /////////创建控件并布局
    topSizer_=new wxBoxSizer(wxVERTICAL);//顶层窗口布局,从上到下包含每个了窗口布局
    wxBoxSizer *firSize=new wxBoxSizer(wxHORIZONTAL);
    wxBoxSizer *secSize=new wxBoxSizer(wxHORIZONTAL);
    wxStaticBox *staticBox=new wxStaticBox(this,wxID_ANY,wxT("注意：双击列表数据可进行修改"));
    wxStaticBoxSizer *thiSize=new wxStaticBoxSizer(staticBox,wxHORIZONTAL);
    wxBoxSizer *bottomSize=new wxBoxSizer(wxHORIZONTAL);
    topSizer_->Add(firSize,0,wxEXPAND|wxALL,0);
    topSizer_->Add(secSize,0,wxEXPAND|wxALL,0);
    topSizer_->Add(thiSize,10,wxEXPAND|wxALL,0);
    topSizer_->Add(bottomSize,0,wxEXPAND|wxALL,0);

    combo_search_=new wxChoice(this,IDC_COMBO_SEARCH);
    combo_id_=new wxComboBox(this,IDC_COMBO_ID);
    btn_Add_Mod_=new wxButton(this,IDC_BTN_ADD_MOD,_T("添加"));
    btn_Del_=new wxButton(this,IDC_BTN_DEL,_T("删除"));
    btn_Exit_=new wxButton(this,IDC_BTN_EXIT,_T("退出"));
    btn_Search_=new wxButton(this,IDC_BTN_SEARCH,_T("查询"));
    text_name_=new wxTextCtrl(this,IDC_EDIT_NAME,wxEmptyString);
    text_search_=new wxTextCtrl(this,IDC_EDIT_SEARCH,wxEmptyString);
    list_=new wxListCtrl(this,IDC_LIST,wxDefaultPosition,wxDefaultSize,wxLC_REPORT|wxLC_SINGLE_SEL);

    firSize->Add(new wxStaticText(this,wxID_ANY,_T("查询类别")),1, wxTILE|wxALL|wxALIGN_RIGHT,5);
    firSize->Add(combo_search_,1, wxEXPAND|wxALL|wxALIGN_CENTER,5);
    firSize->Add(text_search_,1,wxEXPAND|wxALL|wxALIGN_CENTER,5);
    firSize->Add(btn_Search_,1,wxTILE|wxALL|wxALIGN_LEFT,5);
    secSize->Add(new wxStaticText(this,wxID_ANY,_T("类别种类")),1,wxTILE|wxALL|wxALIGN_RIGHT,5);
    secSize->Add(combo_id_,1,wxEXPAND|wxALL|wxALIGN_CENTER,5);
    secSize->Add(new wxStaticText(this,wxID_ANY,_T("类别名称")),1,wxTILE|wxALL|wxALIGN_RIGHT,5);
    secSize->Add(text_name_,1,wxEXPAND|wxALL|wxALIGN_CENTER,5);
    thiSize->Add(list_,1,wxEXPAND | wxALL,5);
    bottomSize->Add(btn_Add_Mod_,1,wxTILE|wxALL|wxALIGN_RIGHT,5);
    bottomSize->Add(btn_Del_,1,wxTILE|wxALL|wxALIGN_CENTER,5);
    bottomSize->Add(btn_Exit_,1,wxTILE|wxALL|wxALIGN_LEFT,5);

    SetSizer(topSizer_);//绑定对话框和布局控件
    SetAutoLayout(true);
    topSizer_->Fit(this);//调用对话框大小
    topSizer_->SetSizeHints(this);//设置对话框最小大小

    ///////创建事件
    Connect(IDC_BTN_ADD_MOD,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&CDlgType::OnBnClickedBtnAddMod);
    Connect(IDC_BTN_EXIT,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&CDlgType::OnBnClickedBtnExit);
    Connect(IDC_BTN_SEARCH,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&CDlgType::OnBnClickedBtnSearch);
    Connect(IDC_BTN_DEL,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&CDlgType::OnBnClickedBtnDel);
    Connect(IDC_LIST,wxEVT_COMMAND_LIST_ITEM_SELECTED,(wxObjectEventFunction)&CDlgType::OnNMClickList);
    Connect(IDC_LIST,wxEVT_COMMAND_LIST_ITEM_ACTIVATED,(wxObjectEventFunction)&CDlgType::OnNMDblclkList);

    wxLogDebug(_T("CreateCtrl"));
}

void CDlgType::EnableAllCtrl( bool isEnable )
{
    if (m_addormod_==ADDMODEL) {
        FindWindowById(IDC_COMBO_ID)->Enable(isEnable);
        FindWindowById(IDC_EDIT_NAME)->Enable(isEnable);
        FindWindowById(IDC_COMBO_SEARCH)->Enable(false);
        FindWindowById(IDC_LIST)->Enable(false);
        FindWindowById(IDC_BTN_SEARCH)->Enable(false);
        FindWindowById(IDC_EDIT_SEARCH)->Enable(false);
        FindWindowById(IDC_BTN_DEL)->Enable(false);
    } else if (m_addormod_==MODMODEL) {
        FindWindowById(IDC_COMBO_ID)->Enable(false);
        FindWindowById(IDC_EDIT_NAME)->Enable(isEnable);
        FindWindowById(IDC_COMBO_SEARCH)->Enable(false);
        FindWindowById(IDC_LIST)->Enable(false);
        FindWindowById(IDC_BTN_SEARCH)->Enable(false);
        FindWindowById(IDC_EDIT_SEARCH)->Enable(false);
        FindWindowById(IDC_BTN_DEL)->Enable(false);
    } else {
        FindWindowById(IDC_COMBO_ID)->Enable(isEnable);
        FindWindowById(IDC_EDIT_NAME)->Enable(isEnable);
        FindWindowById(IDC_COMBO_SEARCH)->Enable(true);
        FindWindowById(IDC_LIST)->Enable(true);
        FindWindowById(IDC_BTN_SEARCH)->Enable(true);
        FindWindowById(IDC_EDIT_SEARCH)->Enable(true);
        FindWindowById(IDC_BTN_DEL)->Enable(true);
    }
    wxLogDebug(_T("EnableAllCtrl"));
}

void CDlgType::InitComboBoxAndListCtrl()
{
    wxChoice *pchoice=wxDynamicCast(FindWindowById(IDC_COMBO_SEARCH),wxChoice);
    wxListCtrl *pList=wxDynamicCast(FindWindowById(IDC_LIST),wxListCtrl);
    pList->SetSingleStyle(wxLC_REPORT);
    pList->SetSingleStyle(wxLC_SINGLE_SEL);
    const vector<pair<wxString,wxString> >&chs_fileds_name=GetFiled_CHS_Name(_T("name_type"));
    auto it=chs_fileds_name.cbegin();
    for (; it!=chs_fileds_name.cend(); ++it) {
        wxLogDebug(_T("%s "),it->first);
        pchoice->Append(it->first);
        pList->InsertColumn(pList->GetColumnCount(),it->first,wxLIST_FORMAT_LEFT,wxLIST_AUTOSIZE);
    }
    pchoice->Refresh();
    pList->Refresh();
    wxComboBox *pBox=wxDynamicCast(FindWindowById(IDC_COMBO_ID),wxComboBox);
    pBox->Append(TYPE_CASH);
    pBox->Append(TYPE_MENU);
    pBox->Refresh();
    wxLogDebug(_T("InitComboBoxAndListCtrl"));
}

void CDlgType::OnBnClickedBtnSearch(wxCommandEvent& event)
{
    wxBusyCursor waticursor;
    wxChoice *pBox=wxDynamicCast(FindWindowById(IDC_COMBO_SEARCH),wxChoice);
    int index=pBox->GetSelection();
    wxString strComboTextFirst,strComboTextSecond;
    if (index == wxNOT_FOUND) {
//        wxLogDebug(_T("查询类别不能为空"));
//        return;
    } else {
        strComboTextFirst=pBox->GetString(index);
    }
    wxListCtrl *pList=wxDynamicCast(FindWindowById(IDC_LIST),wxListCtrl);
    const vector<pair<wxString,wxString> >&chs_filed_name=GetFiled_CHS_Name(_T("name_type"));
    if (chs_filed_name.empty()) {
        return;
    }
    vector<pair<wxString,int> >fileds;
    map<wxString,wxString> condition;
    map<wxString,wxString>*pcondit=NULL;
    auto it=chs_filed_name.cbegin();
    for (; it!=chs_filed_name.cend(); ++it) {
        if (strComboTextFirst==it->first) {
            strComboTextSecond=it->second;
        }
        fileds.push_back(std::make_pair(it->second,(int)FILED_TEXT));
    }
    wxTextCtrl *pText=wxDynamicCast(FindWindowById(IDC_EDIT_SEARCH),wxTextCtrl);
    wxString csEditText=pText->GetValue();
    csEditText.Trim(true);
    csEditText.Trim(false);
    if (!csEditText.IsEmpty() && !strComboTextFirst.IsEmpty()) {
        condition[strComboTextSecond]=csEditText;
        pcondit=&condition;
    }
    SelFromDb(fileds,TABLENAME,pcondit,_T("order by typeid"),pList);
    wxLogDebug(_T("OnBnClickedBtnSearch"));
}
void CDlgType::OnBnClickedBtnDel(wxCommandEvent& event)
{
    wxListCtrl *pList=wxDynamicCast(FindWindowById(IDC_LIST),wxListCtrl);
    long selitemIndex=-1;
    selitemIndex=pList->GetNextItem(selitemIndex,wxLIST_NEXT_ALL,wxLIST_STATE_SELECTED);//得到选中的行数
    if (selitemIndex ==-1) {
        return;
    }
    wxString csid=pList->GetItemText(selitemIndex,0);
    wxString csname=pList->GetItemText(selitemIndex,1);
    wxString tip=_T("确实要删除编号为[")+csid+_T("]，名称为[")+csname+_T("]的类别吗？");
    if(wxNO==wxMessageBox(tip,_T("删除确认"),wxYES_NO)) {
        return;
    }
    map<wxString,wxString> condition;
    condition[_T("typeid")]=wxString::Format(_T("%d"),m_keyvalue_);
    if(DelFromDb(TABLENAME,&condition)) {
        wxMessageBox(_T("删除完成"),_T("删除完成"),wxOK);
        pList->DeleteItem(selitemIndex);
    } else {
        wxMessageBox(sqlite3_errmsg(g_db),_T("删除出错"));
        return;
    }
    wxLogDebug(_T("OnBnClickedBtnDel"));
}
void CDlgType::OnBnClickedBtnExit(wxCommandEvent& event)
{
    if (ADDMODEL==m_addormod_ || MODMODEL==m_addormod_) {
        m_addormod_=-1;
        EnableAllCtrl(false);
        wxButton *pbtn=wxDynamicCast(FindWindowById(IDC_BTN_ADD_MOD),wxButton);
        pbtn->SetLabel(_T("添加"));
        pbtn=wxDynamicCast(FindWindowById(IDC_BTN_EXIT),wxButton);
        pbtn->SetLabel(_T("退出"));
        SetLabel(WINDOWS_TEXT);
    } else {
        Close();
    }
    wxLogDebug(_T("OnBnClickedBtnExit"));
}
void CDlgType::OnBnClickedBtnAddMod(wxCommandEvent& event)
{
    wxString sql;
    wxTextCtrl *pText=wxDynamicCast(FindWindowById(IDC_EDIT_NAME),wxTextCtrl);
    wxString csTypeName=pText->GetValue();
    if (ADDMODEL==m_addormod_) { //由添加转为完成
        wxString typeSuffer;
        wxComboBox *pBox=wxDynamicCast(FindWindowById(IDC_COMBO_ID),wxComboBox);
        wxString strTmp=pBox->GetValue();
        ///1开头表收支类别 2开头表菜式类别
        if (strTmp.CmpNoCase(TYPE_CASH)==0) {
            typeSuffer="1";
        } else if (strTmp.CmpNoCase(TYPE_MENU)==0) {
            typeSuffer="2";
        } else {
            typeSuffer="0";
        }
        //得到新的ID值
        long newID;
        sql=_T("select max(typeid) from ")+TABLENAME;
        sql+=_T(" where typeid like '")+typeSuffer.substr(0,1)+_T("%'");
        sqlite3_stmt *stmt;
        if(sqlite3_prepare_v2(g_db,sql.ToUTF8().data(),strlen(sql.ToUTF8().data()),&stmt,0)==SQLITE_OK) {
            if(sqlite3_step(stmt)==SQLITE_ROW) {
                if(sqlite3_column_text(stmt,0) == NULL) { //无任何记录
                    typeSuffer+=_T("0");
                    typeSuffer.ToLong(&newID);
                } else {
                    newID=sqlite3_column_int(stmt,0);
                }
            }
        } else {
            wxLogDebug(_T("%s 语法有误. 错误信息:%s"), sql,sqlite3_errmsg(g_db));
        }
        if (sqlite3_finalize(stmt) != SQLITE_OK) {
            wxLogDebug(_T("Error on sqlite3_finalize: %s"), sqlite3_errmsg(g_db));
        }
        wxString srctypeSuffer=wxString::Format(_T("%d"),newID);
        wxString newtypeSuffer=wxString::Format(_T("%d"),newID+1);
        if (srctypeSuffer.substr(0,1)!=newtypeSuffer.substr(0,1)) {
            //进位了
            newID=pow(10.,static_cast<long>(srctypeSuffer.size()));
        } else {
            ++newID;
        }
        //添加新记录
        map<wxString,wxString> fileds;
        strTmp=wxString::Format(_T("%d"),newID);
        fileds[_T("typeid")]=strTmp;
        fileds[_T("typename")]=csTypeName;
        wxLogDebug(_T("%s %s"),strTmp,csTypeName);
        if(!AddIntoDb(fileds,TABLENAME)) {
            wxMessageBox(sqlite3_errmsg(g_db),_T("添加出错"));
            return;
        }
        m_addormod_=-1;
        EnableAllCtrl(false);
        wxButton *pbtn=wxDynamicCast(FindWindowById(IDC_BTN_ADD_MOD),wxButton);
        pbtn->SetLabel(_T("添加"));
        pbtn=wxDynamicCast(FindWindowById(IDC_BTN_EXIT),wxButton);
        pbtn->SetLabel(_T("退出"));
        SetLabel(WINDOWS_TEXT);

        //成功把该行插入到list控件中
        wxListCtrl *pList=wxDynamicCast(FindWindowById(IDC_LIST),wxListCtrl);
        pList->InsertItem(pList->GetItemCount(),_T(""));
        pList->SetItem(pList->GetItemCount()-1,1,csTypeName);
        pList->SetItem(pList->GetItemCount()-1,0,strTmp);
    } else if (MODMODEL==m_addormod_) { //由修改转为完成
        if (csTypeName.IsEmpty()) {
            wxMessageBox(_T("类别名称不能为空"),_T("错误"),wxOK);
            return;
        }
        map<wxString,wxString> fileds,condition;
        wxString strTmp=wxString::Format(_T("%d"),m_keyvalue_);
        condition[_T("typeid")]=strTmp;
        fileds[_T("typename")]=csTypeName;
        if(!ModToDb(fileds,TABLENAME,&condition)) {
            wxMessageBox(sqlite3_errmsg(g_db),_T("修改出错"));
            return;
        }
        //成功把修改结果反应到list控件中
        wxListCtrl *pList=wxDynamicCast(FindWindowById(IDC_LIST),wxListCtrl);
        int itemIndex=1;
        itemIndex = pList->GetNextItem(itemIndex,wxLIST_NEXT_ALL,wxLIST_STATE_SELECTED);
        if(itemIndex == -1) {
            return;
        }
        pList->SetItem(itemIndex,1,csTypeName);
        m_addormod_=-1;
        EnableAllCtrl(false);
        wxButton *pbtn=wxDynamicCast(FindWindowById(IDC_BTN_ADD_MOD),wxButton);
        pbtn->SetLabel(_T("添加"));
        pbtn=wxDynamicCast(FindWindowById(IDC_BTN_EXIT),wxButton);
        pbtn->SetLabel(_T("退出"));
        SetLabel(WINDOWS_TEXT);
    } else {
        m_addormod_=ADDMODEL;
        EnableAllCtrl(true);
        wxButton *pbtn=wxDynamicCast(FindWindowById(IDC_BTN_ADD_MOD),wxButton);
        pbtn->SetLabel(_T("完成"));
        pbtn=wxDynamicCast(FindWindowById(IDC_BTN_EXIT),wxButton);
        pbtn->SetLabel(_T("取消添加"));
        SetLabel(WINDOWS_TEXT+_T("_添加"));
        pText->SetLabel(_T(""));
    }
    wxLogDebug(_T("OnBnClickedBtnAddMod"));
}
void CDlgType::OnNMClickList(wxListEvent& event)
{
    if(event.GetIndex()==-1) {
        return;
    }
    wxListCtrl *pList=wxDynamicCast(FindWindowById(IDC_LIST),wxListCtrl);
    wxString strTmp=event.GetText();//得到主键值
    strTmp.ToLong(&m_keyvalue_);
    wxTextCtrl *pText=wxDynamicCast(FindWindowById(IDC_EDIT_NAME),wxTextCtrl);
    pText->SetValue(pList->GetItemText(event.GetIndex(),1));
    ///1开头表收支类别 2开头表菜式类别
    wxComboBox *pBox=wxDynamicCast(FindWindowById(IDC_COMBO_ID),wxComboBox);
    if (strTmp.Left(1)==_T("1")) {
        pBox->SetValue(TYPE_CASH);
    } else if (strTmp.Left(1)==_T("2")) {
        pBox->SetValue(TYPE_MENU);
    } else {
        pBox->SetValue(_T("其他类别"));
    }
    wxLogDebug(_T("OnNMClickList"));
}
void CDlgType::OnNMDblclkList(wxListEvent& event)
{
    if(event.GetIndex()==-1) {
        return;
    }
    wxString strTmp=event.GetText();//得到主键值
    strTmp.ToLong(&m_keyvalue_);
    m_addormod_=MODMODEL;
    EnableAllCtrl(true);
    wxButton *pbtn=wxDynamicCast(FindWindowById(IDC_BTN_ADD_MOD),wxButton);
    pbtn->SetLabel(_T("保存"));//修改完回到待增加状态
    pbtn=wxDynamicCast(FindWindowById(IDC_BTN_EXIT),wxButton);
    pbtn->SetLabel(_T("取消修改"));
    wxString text=WINDOWS_TEXT+_T("_修改");
    SetLabel(text);
    wxLogDebug(_T("OnNMDblclkList"));
}
